<template>
  <div>
    <MyTable :list="list">
      <template #title>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template #main="scope">
        <td>{{ scope.item.id }}</td>
        <td>{{ scope.item.goods_name }}</td>
        <td>{{ scope.item.goods_price }}</td>
        <td>
          <input
            @keyup.esc="escfn(scope.item)"
            @keyup.enter="keyupfn(scope.item)"
            v-model="scope.item.inputValue"
            @blur="scope.item.inputVisible = false"
            class="ipt"
            v-focus
            v-if="scope.item.inputVisible"
            type="text"
            name=""
            id=""
          />
          <button
            v-else
            @click="scope.item.inputVisible = true"
            class="btn btn-primary btn-sm add-tag"
          >
            tags
          </button>
          <span
            class="badge badge-warning"
            v-for="(val, index) in scope.item.tags"
            :key="index"
            >{{ val }}</span
          >
        </td>
        <td>
          <button @click="delfn(scope.index)" class="btn btn-danger btn-sm">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from "../components/MyTable";
export default {
  // 自定义指令
  directives: {
    focus: {
      inserted(el) {
        el.focus(); //自定义指令  自动获取焦点
      },
    },
  },
  components: {
    MyTable,
  },
  data() {
    return {
      list: [],
    };
  },
  async created() {
    const res = await this.$axios({
      url: "/api/goods",
    });
    // console.log(this.list);
    console.log(res.data.data);
    this.list = res.data.data; // 把请求出来的数据给list
  },
  methods: {
    // 删除功能
    delfn(index) {
      this.list.splice(index, 1);
    },
    keyupfn(obj) {
      // console.log(obj.tags);
      obj.tags.push(obj.inputValue);
      obj.inputVisible = false;
    },
    escfn(obj) {
      // 按esc关闭功能
      // console.log(obj);
      obj.inputValue = "";
    },
  },
};
</script>

<style scopedd>
.badge-warning {
  margin: 0 5px;
}
.ipt {
  width: 50px;
  height: 20px;
  outline: none;
}
</style>